import "./index.css";
import { cookies } from "next/headers";
import MoodBankList from "@/components/MoodBankList";
import FriendList from "@/components/FriendList";
import UserInfoCard from "@/components/UserInfoCard";
import styles from "./page.module.css";
import { Card } from "antd";
import MoodNavigation from "@/components/MoodNavigation";
import { headers } from 'next/headers';
import MoodPostBox from '@/components/MoodPostBox';
import HotTopicsCard from "@/components/HotTopicsCard";

// 配置页面选项
// 强制动态渲染
export const dynamic = "force-dynamic";
// 禁用 fetch 缓存
export const fetchCache = 'force-no-store';
// 禁用 ISR 缓存
export const revalidate = 0;

// 禁用所有缓存 已经不再推荐使用
// export const unstable_noStore = true;

interface FriendData {
  userAccount: string;
  userAvatar: string;
  remarks: string;
}

/**
 * 主页：今日心情
 * @constructor
 */
export default async function HomePage({
  searchParams,
}: {
  searchParams: { [key: string]: string | string[] | undefined };
}) {
  let moodBankList: API.FunRiceUser[] = [];
  let friendList: FriendData[] = [];
  const view = searchParams.view || 'mood';
  const timestamp = Date.now();  // 将timestamp提升到函数作用域

  try {
    const cookieStore = cookies();
    const headersList = headers();
    // const timestamp = Date.now();  // 移除这行

    const requestHeaders = {
      "Content-Type": "application/json",
      Cookie: cookieStore.toString(),
      "Cache-Control": "no-cache, no-store, must-revalidate, max-age=0",
      Pragma: "no-cache",
      Expires: "-1",
      // 添加一个随机参数来确保每次请求都是唯一的
      "X-Request-Time": timestamp.toString(),
      // 添加用户标识，确保获取正确的用户数据
      "X-User-Session": cookieStore.toString(),
    };

    // 获取心情列表
    if (view === 'mood') {
      const moodResponse = await fetch(
        `http://localhost:3000/api/rice/list/page?t=${timestamp}`,
        {
          method: "POST",
          headers: requestHeaders,
          cache: "no-store",
          next: { 
            revalidate: 0,
            tags: ['mood-data']
          },
          credentials: "include",
          body: JSON.stringify({
      pageSize: 12,
      sortField: "createTime",
      sortOrder: "desc",
            // 添加时间戳确保每次请求都是新的
            _t: timestamp
          }),
        },
      );

      const moodRes = await moodResponse.json();
      if (moodRes?.data) {
        moodBankList = Array.isArray(moodRes.data) ? moodRes.data : [];
      }
    }

    // 获取好友列表
    if (view === 'friends') {
      const friendResponse = await fetch(
        `http://localhost:3000/api/rice/query/friend/list?t=${timestamp}`,
        {
          method: "POST",
          headers: requestHeaders,
          cache: "no-store",
          next: { 
            revalidate: 0,
            tags: ['friend-data']
          },
          credentials: "include",
          body: JSON.stringify({
            // 添加时间戳确保每次请求都是新的
            _t: timestamp
          }),
        }
      );

      const friendRes = await friendResponse.json();
      if (friendRes?.code === 0 && friendRes?.data) {
        friendList = Array.isArray(friendRes.data) ? friendRes.data : [];
      }
    }
  } catch (error) {
    console.error("Failed to fetch data:", error);
  }

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.sideNav}>
          <MoodNavigation view={view as string} styles={styles} />
        </div>
        <div className={styles.mainContent}>
          <MoodPostBox />
          {view === 'mood' ? (
            <MoodBankList moodBankList={moodBankList} />
          ) : (
            <Card>
              <FriendList key={timestamp} friendList={friendList} />
            </Card>
          )}
        </div>
        <div className={styles.sideContent}>
          <UserInfoCard/>
          <div style={{ marginTop: 16 }}></div>
          <HotTopicsCard />
        </div>
      </div>
    </div>
  );
}
